import 'package:flutter/material.dart';
import '../../widgets/rich_text_display.dart';
import '../../widgets/rich_text_viewer.dart';
import '../../models/post_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import 'package:base_flutter/src/network/network_exception.dart';

/// 文章详情页面
/// 显示文章的完整内容，包括标题、作者信息、正文等
class ArticleDetailPage extends StatefulWidget {
  final PostModel post;

  const ArticleDetailPage({
    super.key,
    required this.post,
  });

  @override
  State<ArticleDetailPage> createState() => _ArticleDetailPageState();
}

class _ArticleDetailPageState extends State<ArticleDetailPage> {
  ArticleModel? _article;
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadArticleDetail();
  }

  /// 加载文章详情
  Future<void> _loadArticleDetail() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      final article = await ApiService().getArticleDetail(widget.post.id);
      
      setState(() {
        _article = article;
        _isLoading = false;
      });

      Logger.d('ARTICLE_DETAIL', '文章详情加载成功');
    } catch (e) {
      Logger.e('ARTICLE_DETAIL', '文章详情加载失败: $e');
      setState(() {
        _error = e is NetworkException ? e.message : '加载失败';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('文章详情'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: _handleShare,
          ),
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: _showMoreOptions,
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              _error!,
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadArticleDetail,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_article == null) {
      return const Center(
        child: Text('文章不存在'),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文章标题
          Text(
            _article!.title,
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              height: 1.3,
            ),
          ),
          const SizedBox(height: 16),
          
          // 作者信息
          _buildAuthorInfo(),
          const SizedBox(height: 24),
          
          // 文章摘要
          if (widget.post.summary != null && widget.post.summary!.isNotEmpty) ...[
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey[200]!),
              ),
              child: Text(
                widget.post.summary!,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[700],
                  height: 1.5,
                ),
              ),
            ),
            const SizedBox(height: 24),
          ],
          
          // 文章正文
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[200]!),
            ),
            child: _buildArticleContent(),
          ),
          const SizedBox(height: 24),
          
          // 互动区域
          _buildInteractionArea(),
          const SizedBox(height: 24),
          
          // 技能标签
          if (widget.post.skillTags.isNotEmpty) ...[
            _buildSkillTags(),
            const SizedBox(height: 24),
          ],
          
          // 相关推荐
          _buildRelatedArticles(),
        ],
      ),
    );
  }

  /// 构建文章内容（支持HTML富文本）
  Widget _buildArticleContent() {
    final content = _article!.contentHtml;
    
    // 检查内容是否包含HTML标签
    final bool isHtml = content.contains('<') && content.contains('>');
    
    if (isHtml) {
      // 使用HTML渲染器
      return RichTextViewer(
        htmlContent: content,
        defaultTextStyle: const TextStyle(
          fontSize: 16,
          height: 1.6,
          color: Colors.black87,
        ),
      );
    } else {
      // 纯文本或自定义格式，使用简化显示
      return SimpleRichTextDisplay(
        content: content,
        textStyle: const TextStyle(
          fontSize: 16,
          height: 1.6,
          color: Colors.black87,
        ),
      );
    }
  }

  /// 构建作者信息
  Widget _buildAuthorInfo() {
    return Row(
      children: [
        CachedAvatarWidget(
          avatarUrl: widget.post.userAvatar,
          size: 48,
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.post.username,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 4),
              Row(
                children: [
                  Icon(
                    Icons.location_on,
                    size: 14,
                    color: Colors.grey[600],
                  ),
                  const SizedBox(width: 4),
                  Text(
                    widget.post.location ?? '',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    _getTimeAgo(widget.post.createdAt),
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        ElevatedButton(
          onPressed: _handleFollow,
          child: const Text('关注'),
        ),
      ],
    );
  }

  /// 构建互动区域
  Widget _buildInteractionArea() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildInteractionButton(
            icon: widget.post.isLiked ? Icons.favorite : Icons.favorite_border,
            label: '${widget.post.likesCount}',
            color: widget.post.isLiked ? Colors.red : Colors.grey[600],
            onTap: _handleLike,
          ),
          _buildInteractionButton(
            icon: Icons.comment,
            label: '${widget.post.commentsCount}',
            color: Colors.grey[600],
            onTap: _handleComment,
          ),
          _buildInteractionButton(
            icon: Icons.share,
            label: '${widget.post.sharesCount}',
            color: Colors.grey[600],
            onTap: _handleShare,
          ),
          _buildInteractionButton(
            icon: Icons.visibility,
            label: '${widget.post.viewsCount}',
            color: Colors.grey[600],
            onTap: () {},
          ),
        ],
      ),
    );
  }

  /// 构建互动按钮
  Widget _buildInteractionButton({
    required IconData icon,
    required String label,
    required Color? color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Icon(
            icon,
            color: color,
            size: 24,
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              color: color,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建技能标签
  Widget _buildSkillTags() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '相关标签',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: widget.post.skillTags.map((tag) {
            return Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(16),
                border: Border.all(
                  color: Theme.of(context).primaryColor.withOpacity(0.3),
                ),
              ),
              child: Text(
                tag,
                style: TextStyle(
                  color: Theme.of(context).primaryColor,
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }

  /// 构建相关文章推荐
  Widget _buildRelatedArticles() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '相关推荐',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Container(
          height: 200,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: 3, // 模拟数据
            itemBuilder: (context, index) {
              return Container(
                width: 200,
                margin: const EdgeInsets.only(right: 12),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey[200]!),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      height: 100,
                      decoration: BoxDecoration(
                        color: Colors.grey[200],
                        borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(8),
                          topRight: Radius.circular(8),
                        ),
                      ),
                      child: const Center(
                        child: Icon(Icons.article, size: 40),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(12),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '相关文章标题 ${index + 1}',
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 8),
                          Text(
                            '作者名称',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  /// 处理点赞
  void _handleLike() async {
    try {
      await ApiService().likePost(widget.post.id, !widget.post.isLiked);
      
      setState(() {
        // 更新点赞状态
        // 这里需要更新widget.post的状态，但由于是final，需要重新构建
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(!widget.post.isLiked ? '已点赞' : '已取消点赞'),
        ),
      );
    } catch (e) {
      Logger.e('ARTICLE_DETAIL', '点赞失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理评论
  void _handleComment() {
    // TODO: 实现评论功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('评论功能开发中...')),
    );
  }

  /// 处理分享
  void _handleShare() async {
    try {
      await ApiService().sharePost(widget.post.id);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('分享成功')),
      );
    } catch (e) {
      Logger.e('ARTICLE_DETAIL', '分享失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('分享失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理关注
  void _handleFollow() {
    // TODO: 实现关注功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('关注功能开发中...')),
    );
  }

  /// 显示更多选项
  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.bookmark_border),
              title: const Text('收藏'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('收藏功能开发中...')),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.report),
              title: const Text('举报'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('举报功能开发中...')),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 获取时间差
  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  /// 处理HTML内容，确保图片能正确显示
  String _processHtmlContent(String htmlContent) {
    if (htmlContent.isEmpty) return '';
    
    // 处理自定义图片标记 [图片:URL] 转换为HTML img标签
    String processedContent = htmlContent.replaceAllMapped(
      RegExp(r'\[图片:([^\]]+)\]'),
      (match) {
        String imageUrl = match.group(1) ?? '';
        return '<img src="$imageUrl" alt="图片" style="max-width: 100%; height: auto; margin: 8px 0; border-radius: 8px;" />';
      },
    );
    
    // 处理Markdown格式的图片 ![alt](url)
    processedContent = processedContent.replaceAllMapped(
      RegExp(r'!\[([^\]]*)\]\(([^)]+)\)'),
      (match) {
        String alt = match.group(1) ?? '图片';
        String url = match.group(2) ?? '';
        return '<img src="$url" alt="$alt" style="max-width: 100%; height: auto; margin: 8px 0; border-radius: 8px;" />';
      },
    );
    
    // 确保所有img标签都有正确的样式
    processedContent = processedContent.replaceAllMapped(
      RegExp(r'<img([^>]*)>'),
      (match) {
        String attributes = match.group(1) ?? '';
        if (!attributes.contains('style=')) {
          attributes += ' style="max-width: 100%; height: auto; margin: 8px 0; border-radius: 8px;"';
        }
        return '<img$attributes>';
      },
    );
    
    Logger.d('ARTICLE_DETAIL', '处理后的HTML内容: $processedContent');
    return processedContent;
  }
}
